// @author    Coolman <QQ Group ID: 892850160>
(() => {
    const toasta = (message) => {
        toast(message);
        sleep(1000);
    };
    const toastLoga = (message) => {
        toastLog(message);
        sleep(1000);
    };
    const boundsCenter = (node) => {
        let bounds = node.bounds();
        return [random(-5, 5) + bounds.centerX(), random(-3, 3) + bounds.centerY()];
    };
    const findFirstScrollable = () => {
        let i;
        selector().find().forEach((item) => {
            if (item.scrollable()) {
                i = item;
                return;
            }
        });
        return i;
    };
    const findTextWidget = (str) => {
        for (let swipeTimes = 0; !text(str).exists(); swipeTimes++) {
            // let x1 = device.width - random(200, 300);
            // let y1 = device.height - random(400, 500);
            // let deltaX = random(20, 40);
            // let deltaY = random(400, 500);
            // let duration = random(500, 600);
            // // Android 7.0 +
            // swipe(x1, y1, x1 + deltaX, y1 - deltaY, duration);
            // gesture(duration, [x1, y1], [x1 + deltaX, y1 - deltaY]);
            const fs = findFirstScrollable();
            if (!fs) {
                toasta('cannot find scrollable');
                return false;
            }
            fs.scrollForward();
            sleep(500);
            if (swipeTimes > 10) {
                toasta(str + ' 没找到');
                return false;
            }
        }
        return true;
    };

    auto.waitFor();

    const jdPackName = 'com.jingdong.app.mall',
        jdMainAct = jdPackName + '.MainFrameActivity'
        webAct = jdPackName + '.WebActivity';
    const defautWaitTime = 5000;
    if (jdPackName != currentPackage()) {
        toasta('打开京东...');
        let t = threads.start(function() {
            launch(jdPackName);
            waitForActivity(jdMainAct);
        });
        t.join(defautWaitTime);
    } else {
        console.log('already in jd app');
    }

    switch (currentActivity()) {
        case jdMainAct:
            console.log('already in main activity');
            const btn = desc('我的').findOne();
            let [x, y] = btn && boundsCenter(btn);
            toasta('点击我的');
            click(x, y);
            toasta('搜索全民炸年兽');
            if (!findTextWidget('全民炸年兽')) {
                return;
            } else {
                let zha = text('全民炸年兽').findOne();
                let [x, y] = boundsCenter(zha.parent());
                toasta('打开全民炸年兽');
                let t = threads.start(function() {
                    click(x, y);
                    waitForActivity(webAct);
                });
                t.join(defautWaitTime);
            }
            break;
        case webAct:
            console.log('already in web activity');
            break;
        default:
            toastLoga(currentActivity());
            exit();
            return;
    }

    toasta('找到做任务拿爆竹');
    if (!findTextWidget('做任务拿爆竹')) {
        return;
    } else {
        let zha = text('做任务拿爆竹').findOne();
        toasta('点击做任务拿爆竹');
        let [x, y] = boundsCenter(zha);
        click(x, y);
    }

    let one = textContains('次)').findOne(5000);
    if (!one) {
        toastLoga('找不到 领爆竹');
        exit();
        return;
    }

    const exclusions = ['邀请好友助力', '开启LBS定位', '逛年货节主会场',];
    const reg = new RegExp(exclusions.join('|'));
    let todo = [];
    textContains('次)').find().forEach((item) => {
        !reg.test(item.text()) && todo.push(item);
    });
    console.log('todo.length:', todo.length);
    const clickAndBack = (node) => {
        node.clickable() && node.click();
        sleep(2000);
        let t = threads.start(function() {
            back();
            waitForActivity(webAct);
        });
        t.join(defautWaitTime);
    };
    const progressReg = /(\d{1,2})\/(\d{1,2})/;
    let counter = 0;
    for (let item of todo) {
        (sync((item) => {
            const nodes = item.parent().children();
            // console.log(i, nodes[i]);
            if (nodes.length < 4) {
                return;
            }
            let found = item.text().match(progressReg);
            if (!found) {
                return;
            }
            let [done, all] = [+found[1], +found[2]];
            if (done == all) {
                counter++;
                return;
            }
            for (; done < all; done++) {
                console.log('info', all, done);
                clickAndBack(nodes[3]);
                sleep(1000);
            }
            toastLoga(item.text() + ' 已完成');
            toastLoga('todo: ' + todo.length + ', done: ' + counter);
        }))(item);
    }
    if (counter == todo.length) {
        toastLoga('*** all is done ***');
    }
})();
